package gui 
{
	import fl.controls.TileList;
	import fl.events.ScrollEvent;
	import flash.events.Event;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class Binder 
	{
		private var _tileList:TileList;
		private var _scrollBar:ScrollBar;
		
		private var _master:Object;
		// TODO check scrollbar type
		
		private var _scrollBarType:String;
		
		public function Binder() 
		{
			
		}
		
		public function bind(tileList:TileList, scrollBar:ScrollBar, scrollBarType:String):void
		{
			_scrollBarType = scrollBarType;
			// clear if exist
			if (_tileList != null)
			{
				_tileList.removeEventListener(ScrollEvent.SCROLL, handleTileListScroll);
			}
			if (_scrollBar != null)
			{
				_scrollBar.removeEventListener(Event.CHANGE, handleScrollChange); 
			}
			_tileList = tileList;
			_scrollBar = scrollBar;
			
			
			/*if (_tileList.maxVerticalScrollPosition != 0)
			{
				_scrollBar.silentSetValue(_tileList.verticalScrollPosition / _tileList.maxVerticalScrollPosition);
			}else
			{
				_scrollBar.silentSetValue(0);
			}*/
			_tileList.addEventListener(ScrollEvent.SCROLL, handleTileListScroll);
			_scrollBar.addEventListener(Event.CHANGE, handleScrollChange); 
			handleTileListScroll(null);
		}
		
		private function handleScrollChange(e:Event):void 
		{
			_master = _scrollBar;
			if (_scrollBarType == ScrollBar.VERTICAL)
			{
				_tileList.verticalScrollPosition = 
					_tileList.maxVerticalScrollPosition * _scrollBar.scrollPercent;
			}else if (_scrollBarType == ScrollBar.HORIZONTAL)
			{
				_tileList.horizontalScrollPosition = 
					_tileList.maxHorizontalScrollPosition * _scrollBar.scrollPercent;
			}
		}
		
		private function handleTileListScroll(e:ScrollEvent):void 
		{
			if (_master != _scrollBar)
			{
				if (_scrollBarType == ScrollBar.VERTICAL)
				{
					_scrollBar.silentSetValue(_tileList.verticalScrollPosition / _tileList.maxVerticalScrollPosition);
				}else if (_scrollBarType == ScrollBar.HORIZONTAL)
				{
					_scrollBar.silentSetValue(_tileList.horizontalScrollPosition / _tileList.maxHorizontalScrollPosition);
				}
			}else
			{
				_master = null;
			}
			
		}
		
	}

}